const http = require('http')

const HttpRequest = function() {
  this.query = ''
}

function HttpResponse() {
  this.body = []
  this.status = 404;
  this.contentType = 'text/plain'
}

HttpResponse.prototype.write = function(block) {
  this.body.push(block)
}

HttpResponse.prototype.display = function() {
  console.log(this.body, this.status)
}

const HttpApplication = function() {
  this.caches = []
}

HttpApplication.prototype.use = function(middleware) {
  // console.log(this.caches)
  this.caches.push(middleware)
}

HttpApplication.prototype._createPipeLineItem = (fn, next) => {
  return (req, rsp) => {
    fn.call(this, req, rsp, next)
  }
}

HttpApplication.prototype.applyRequest = function(req, rsp) {

  const middleware = this.caches.map(item => item).reverse()

  let lastHandler = (req, rsp) => {
    rsp.write('404')
    rsp.status = 404
  }

  for (let index = 0; index < middleware.length; index++) {
    const element = middleware[index];
    lastHandler = this._createPipeLineItem(element, lastHandler)
  }

  lastHandler(req, rsp)
}

const app = new HttpApplication()
app.use((req, rsp, next) => {
  rsp.contentType = 'text/html'
  rsp.write('<h1>first middleware</h1>')
  next(req, rsp)
  // rsp.write('first middleware end')
})


app.use((req, rsp, next) => {
  rsp.write('<h2>second middleware</h2>')
  rsp.status = 200
  // next(req, rsp)
})



// const req = new HttpRequest()
const rsp = new HttpResponse()

const server = http.createServer(function(request, response){
  

  rsp.body = [];

  app.applyRequest(request, rsp)

  response.writeHead(rsp.status, { 'content-type': rsp.contentType })

  const body =  rsp.body.join('')

  response.end(body)
});

server.listen(4000)
console.log('create server listen 4000')


// rsp.display()


